package com.mmall.common;

import com.mmall.util.PropertyUtil;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.*;
import redis.clients.util.Hashing;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Created by root on 18-4-30.
 */

public class RedisShardedPool {

    private static ShardedJedisPool shardedJedisPool;
    private static Integer maxTotal = Integer.parseInt(PropertyUtil.getProperty("redis.max.total", "20"));
    private static Integer maxIdle = Integer.parseInt(PropertyUtil.getProperty("redis.max.idle", "10"));
    private static Integer minIde = Integer.parseInt(PropertyUtil.getProperty("redis.min.idle", "2"));
    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertyUtil.getProperty("redis.test.onBorrow", "true"));
    private static Boolean testOnReTurn = Boolean.parseBoolean(PropertyUtil.getProperty("redis.test.onReturn", "false"));
    private static String  redis1Ip = PropertyUtil.getProperty("redis1.ip");
    private static Integer redis1Port = Integer.parseInt(PropertyUtil.getProperty("redis1.port", "6379"));

    private static String  redis2Ip = PropertyUtil.getProperty("redis2.ip");
    private static Integer redis2Port = Integer.parseInt(PropertyUtil.getProperty("redis2.port", "6380"));

    private static Integer timeout = Integer.parseInt(PropertyUtil.getProperty("redis.timeout", "2")); //unit:second

    static {
        initPool();
    }

    private static void initPool () {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMinIdle(minIde);
        poolConfig.setTestOnBorrow(testOnBorrow);
        poolConfig.setTestOnReturn(testOnReTurn);
        poolConfig.setBlockWhenExhausted(true);

        JedisShardInfo jedisShardInfo1 = new JedisShardInfo(redis1Ip, redis1Port, timeout);
        JedisShardInfo jedisShardInfo2 = new JedisShardInfo(redis2Ip, redis2Port, timeout);
        List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>(2);
        jedisShardInfoList.add(jedisShardInfo1);
        jedisShardInfoList.add(jedisShardInfo2);
        shardedJedisPool = new ShardedJedisPool(poolConfig, jedisShardInfoList, Hashing.MURMUR_HASH);
    }

    public static ShardedJedis getResource(){
        return shardedJedisPool.getResource();
    }

    public static void returnResource(ShardedJedis jedis) {
        shardedJedisPool.returnResource(jedis);
    }

    public static void returnBrokenResource(ShardedJedis jedis) {
        shardedJedisPool.returnBrokenResource(jedis);
    }

    public static void main(String[] args) {
        ShardedJedis jedis = getResource();
        for (int i = 10 ; i < 20 ; i++) {
            jedis.set("key" + i, "value" + i);
        }
        returnResource(jedis);
        System.out.println("test end");
    }


}
